<template>
  <view :class="theme">
    <view class="fixed" style="left: var(--window-left); right: var(--window-right); top: 0; bottom: 0;">
      <uv-image width="100%" height="100%" src="/static/img/img-auth.png" />
    </view>

    <view class="z-1 min-h-100vh color-15" style="padding: 500rpx 40rpx 88rpx;">
      <view class="flex-row relative">
        <label @click="switchTab(index)" v-for="(option, index) in tabs.list" :key="index"
          :class="[`opacity-${index === tabs.current ? `10` : `06`}`, `text-36 fw-700 flex-1 justify-center pb-20`]"
          style="transition: color 0.3s linear;">
          {{ option }}
        </label>
        <view class="absolute bottom-0 h-8 bg-2 b-rounded-6"
          :style="{ width: `80rpx`, transition: `left 0.2s linear`, transform: `translateX(-50%)`, left: `calc(100% / ${tabs.list.length} / 2 + 100% / ${tabs.list.length} * ${tabs.current})`, }" />
      </view>

      <view class="mt-60 pl-40 b-rounded-50 text-28 h-100" style="border: 1rpx solid #a4a4a4;">
        <input v-model="formData.phoneNumber.value" class="h-full text-28" type="number" placeholder="请输入手机号码"
          maxlength="11" />
      </view>

      <view v-if="tabs.current" class="mt-30 pl-40 b-rounded-50 text-28 h-100 flex-row b-rounded-50 overflow-hidden"
        style="border: 1rpx solid #a4a4a4;">
        <input @confirm="login" v-model="formData.captcha.value" class="flex-1 h-full text-28" type="number"
          placeholder="请输入短信验证码" maxlength="6" confirm-type="next" />
        <button @click="getCaptcha" :disabled="formData.captcha.disabled" hover-class="op-[0.6]"
          style="line-height: 100rpx; width: 220rpx;" class="bg-5 text-32 color-2 fw-600 b-rounded-0">
          {{ formData.captcha.text }}
        </button>
      </view>

      <view v-else class="mt-30 pl-50 pr-30 bg-0 b-rounded-50 text-28 h-100 flex-row items-center"
        style="border: 1rpx solid #a4a4a4;">
        <input @confirm="login" v-model="formData.password.value" class="flex-1 h-full text-28"
          :type="formData.password.isVisible ? `text` : `password`" placeholder="請輸入登錄密碼" maxlength="16"
          confirm-type="next" />
        <button @click="formData.password.isVisible = !formData.password.isVisible"
          class="bg-0 color-2 items-end justify-center text-28 fw-600 b-rounded-0 w-100 h-100">
          <uv-icon size="36" color="#fff" :name="`${formData.password.isVisible ? `eye-off-outline` : `eye`}`" />
        </button>
      </view>

      <view class="mt-42 flex-row justify-between items-center text-28">
        <view @click="uniNavigator({ url: `/pages/client/auth/register`, type: 'redirectTo' })"
          class="flex-row text-28 items-center" hover-class="op-[0.6]">
          <text>没有账号？</text>
          <text style="text-decoration: underline;">立即注册</text>
        </view>

        <navigator url="/pages/client/auth/reset" hover-class="op-[0.6]">找回密码</navigator>
      </view>

      <button @click="login" hover-class="op-[0.6]" style="line-height: 100rpx; margin: 90rpx 0;"
        class="bg-5 text-32 color-2 fw-700 b-rounded-50">登录</button>

      <label class="justify-center">
        <switch :checked="formData.isAgree.value" @change="(e: any) => formData.isAgree.value = e.detail.value"
          :color="$config.COLOR_2" type="checkbox" />
        <view class="flex-row">
          <text>我已阅读并同意</text>
          <navigator @click.stop.prevent :url="buildDocumentURL('服务协议', '/userAgreementInfo')" hover-class="op-[0.6]"
            style="text-decoration: underline;" class="color-5">
            《服务条款》
          </navigator>
          <text>和</text>
          <navigator @click.stop.prevent :url="buildDocumentURL('隐私政策', '/privateInfo')" hover-class="op-[0.6]"
            style="text-decoration: underline;" class="color-5">
            《隐私政策》
          </navigator>
        </view>
      </label>
    </view>
    <ali-awsc v-show="awsc.show" @click="awsc.show = false" @success="getCaptcha" :scene="awsc.scene"
      :appkey="awsc.appkey" />

    <uv-modal @confirm="confirmPrompt" :ref="(e: AnyObject) => (showPopup.prompt = e)" :cancel-color="$config.COLOR_9"
      :bgColor="$config.COLOR_4" :confirm-color="$config.COLOR_5" title="服务协议和隐私政策" content="确定已阅读并同意服务协议和隐私政策"
      confirm-text="同意" cancel-text="拒绝" showCancelButton>
      <view class="overflow-hidden block w-full text-24 lh-[2]">
        <text>为了更好的向你提供服务，请您阅读并同意以下协议</text>
        <navigator class="color-5 inline-flex underline" :url="buildDocumentURL('服务条款', '/userAgreementInfo')">
          《服务条款》
        </navigator>
        <text>和</text>
        <navigator class="color-5 inline-flex underline" :url="buildDocumentURL('隐私政策', '/privateInfo')">
          《隐私政策》
        </navigator>
      </view>
    </uv-modal>
  </view>
</template>

<script lang="ts" setup>
import { checkVersion } from "@/common/libs/dependency";
import { useMapState } from "@/common/libs/store";
import { getClient, pickObjectProperty, transformURL, uniNavigator } from "@/common/libs/utils";
import { onLoad } from "@dcloudio/uni-app";
import { reactive } from "vue";

const { $config = {} } = getApp().globalData || {};
const { theme } = useMapState(["theme"]);
const buildDocumentURL = (title: string, api: string) => transformURL("/pages/common/webview",
  {
    title: encodeURIComponent(title),
    url: encodeURIComponent(transformURL("/html/document.html",
      { title },
      $config.URL_REMOTE + $config.API_PREFIX + api
    ))
  }
);

const showPopup = reactive({
  prompt: {} as AnyObject,
});

const formData = reactive({
  phoneNumber: {
    value: "",
    errorMessage: "手机号码输入有误",
    field: "mobile",
    rule: /^1[0-9]{10}$/
  },
  password: {
    value: "",
    errorMessage: "请输入密码",
    field: "password",
    isVisible: false,
    rule: /^.+$/
  },
  captcha: {
    text: "获取验证码",
    errorMessage: "验证码输入有误",
    disabled: false,
    count: 60,
    timer: null as any,
    value: "",
    field: "code",
    rule: /^[0-9]{4,8}$/
  },
  isAgree: {
    value: false,
    rule: /true/
  }
});

const tabs = reactive({
  current: 0,
  list: ["密码登录", "验证码登录"]
});

const awsc = reactive({
  show: false,
  scene: "nc_login_h5",
  appkey: "FFFF0N0000000000B4D6",
});
let wv: any;
const getCaptcha = ({ sessionId, sig, token }: AnyObject) => {
  const { captcha, phoneNumber } = formData;
  if (captcha.disabled) return;

  const requestSendSms = ({ sessionId, sig, token }: AnyObject) => {
    uni.showToast({ icon: "loading", mask: true });
    uni.request({
      url: "/sendSms",
      data: {
        mobile: formData.phoneNumber.value,
        type: "fastLogin",
        sessionId, sig, token,
        scene: awsc.scene
      },
      success({ msg: title }: any) {
        uni.showToast({ title, icon: "none" });
      }
    });
    countDown();
  }

  if (!phoneNumber.rule.test(phoneNumber.value)) {
    uni.showToast({
      title: phoneNumber.errorMessage,
      icon: "none"
    });
    return;
  }

  // #ifdef APP-PLUS
  if (wv) return wv.show();

  wv = plus.webview.create('/static/server/html/verify.html', 'custom-webview', {
    'uni-app': 'none',
    background: 'transparent',
    webviewBGTransparent: true,
    height: "100%",
    width: "100%",
    top: "0"
  } as any, {
    appkey: awsc.appkey,
    scene: awsc.scene
  });
  const pages = getCurrentPages();
  const currentPages: any = pages[pages.length - 1];
  const currentWebview = currentPages.$getAppWebview();
  currentWebview.append(wv);

  (plus as any).globalEvent.addEventListener('plusMessage', (msg: any) => {
    const result = msg.data.args.data
    if (result.name == 'postMessage') {
      requestSendSms(result.arg);
      return;
    }
  })
  // #endif

  if (!awsc.show) {
    awsc.show = true;
    return;
  }
  awsc.show = false;
  requestSendSms({ sessionId, sig, token });
}

onLoad(() => {
  [5, 6, 9, 10].includes(getClient()) && checkVersion();
});

const countDown = () => {
  const { captcha } = formData;
  captcha.disabled = true;

  const intervalTask = () => {
    captcha.count--;
    captcha.text = `${captcha.count}S`;

    if (captcha.count <= 0) {
      captcha.disabled = false;
      captcha.text = "重新获取";
      captcha.count = 60;
      captcha.timer && clearInterval(captcha.timer);
      captcha.timer = null;
    }
    return intervalTask;
  }
  captcha.timer = setInterval(intervalTask(), 1000);
}

const switchTab = (index: number) => {
  if (index === tabs.current) return;
  tabs.current = index;
}

const confirmPrompt = () => {
  formData.isAgree.value = true;
  showPopup.prompt.close();
  login();
}

const login = () => {
  const params = pickObjectProperty(["phoneNumber", tabs.current ? "captcha" : "password"], formData);

  const data: any = {},
    verification = (<Array<keyof typeof params>>Object.keys(params)).every(key => {
      const { value, field, errorMessage: title, rule } = params[key] as any;

      if (title && !rule.test(String(value))) {
        uni.showToast({ title, icon: "none" });
        return false;
      }

      field && (data[field] = value);
      return true;
    });

  if (!verification) return;

  if (!formData.isAgree.value) {
    showPopup.prompt.open();
    return;
  }

  uni.showToast({ icon: "loading", mask: true });
  uni.request({
    url: ["/login", "/fastLogin"][tabs.current], data,
    async success({ data }: any) {
      uni.hideToast();
      await uni.setStorage({
        key: $config.STORAGE_KEY_USER_INFO,
        data: { value: data, expireTime: $config.STORAGE_USER_INFO_EXPIRE_TIME },
      });
      uni.reLaunch({ url: $config.PAGE_HOME_CLIENT });
    }
  });
}


</script>

<style lang="scss" scoped>
// scss
::v-deep {
  button[disabled] {
    opacity: 0.6;
  }

  switch {
    transform: scale(0.7);

    .wx-checkbox-input,
    .uni-checkbox-input {

      &:empty,
      &.wx-checkbox-input-checked,
      &.uni-checkbox-input-checked {
        border-color: $uni-color-primary;
        background-color: transparent;
      }

      &:not(:empty) {
        border-color: transparent;
        background: $uni-bg-color-primary;
      }

      border-width: 2px;
      border-radius: 50%;
    }

    &:not([disabled]) {

      .wx-checkbox-input:hover,
      .uni-checkbox-input:hover {
        border-color: $uni-bg-color-primary;
      }
    }
  }
}
</style>